package com.jzo2o.foundations.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeItemService;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 区域服务表 服务实现类
 * </p>
 * @author dmr
 * @since 2024-10-27
 */
@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Autowired
    private IServeService serveService;
    @Autowired
    private IServeItemService serveItemService;
    @Autowired
    private RegionMapper regionMapper;

    /**
     * 条件分页查询
     * @param servePageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<ServeResDTO> pageByReginIdQuery(ServePageQueryReqDTO servePageQueryReqDTO) {
        //判断数据有效性
        return PageHelperUtils.selectPage(servePageQueryReqDTO,
                () -> baseMapper.queryByReginId(servePageQueryReqDTO.getRegionId()));
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<ServeUpsertReqDTO> list) {
        //参数校验
        if(CollectionUtil.isEmpty(list)){
            throw new CommonException("批量新增服务参数不能为空");
        }
        //存放批量增加的服务数据
        List<Serve> arrayList = new ArrayList<>();
        //遍历判断所需添加的服务项目是否存在
        list.forEach(e ->{
            ServeItem serveItem = serveItemService.getById(e.getServeItemId());
            if (ObjectUtil.isNull(serveItem)) {
            throw new CommonException("添加的目标服务不存在");
        } else{
                //判断该服务是否已经添加过
                Integer count = serveService.lambdaQuery().eq(Serve::getServeItemId, e.getServeItemId())
                        .eq(Serve::getRegionId, e.getRegionId()).count();
                if(count != FoundationStatusEnum.INIT.getStatus()){
                    //说明已经存在当前服务项目
                    throw new CommonException("当前区域不能添加重复服务项目");
                }
                //数据封装
                //业务处理 获取city_code
                Region region = regionMapper.selectById(e.getRegionId());
                if(!ObjectUtils.isEmpty(region)){
                    Serve serve = new Serve();
                    BeanUtil.copyProperties(e,serve);
                    serve.setCityCode(region.getCityCode());
                    arrayList.add(serve);
                }
            }
        });
        serveService.saveBatch(arrayList);
    }

    /**
     * 修改价格
     * @param serveId
     * @param price
     */
    @Override
    public void update(Long serveId, Double price) {
        //参数校验
        if(serveId == null && price == null){
            throw new CommonException("更新服务价格参数不能为空");
        }
        //当前服务是否存在
        if(ObjectUtils.isEmpty(serveService.getById(serveId))){
            throw new CommonException("当前修改目标服务不存在");
        }
        if(price <= 0){
            throw new CommonException("服务价格必须大于0");
        }
        //处理更新业务
        serveService.update(new LambdaUpdateWrapper<Serve>()
                .eq(Serve::getId, serveId)
                .set(Serve::getPrice, price));
    }

    /**
     * 上架服务
     * @param serveId
     */
    @Override
    public void onSale(Long serveId) {
        //参数校验
        if(serveId == null){
            throw new CommonException("参数不能为空");
        }
        Serve serve = serveService.getById(serveId);
        if(ObjectUtils.isEmpty(serve)){
            throw new CommonException("当前服务不存在");
        }
        ServeItem item = serveItemService.lambdaQuery().eq(ServeItem::getId, serve.getServeItemId()).one();
        //判断当前服务所属项目是否处于启用状态
        if(item.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()){
            throw new CommonException( item.getName() + "服务项目未启用");
        }
        //判断当前服务是否处于草稿或者下架
        if(serve.getSaleStatus() == FoundationStatusEnum.ENABLE.getStatus()){
            throw new CommonException(item.getName() +  "服务已处于上架状态");
        }
        //业务处理
        //将服务状态改为上架
        serveService.lambdaUpdate()
                .eq(Serve::getId, serveId).setSql("sale_status = " + FoundationStatusEnum.ENABLE.getStatus())
                .update();
    }

    /**
     * 下架服务
     * @param serveId
     */
    @Override
    public void offSale(Long serveId) {
        //参数校验
        if(serveId == null){
            throw new CommonException("参数不能为空");
        }
        Serve serve = serveService.getById(serveId);
        if(ObjectUtils.isEmpty(serve)){
            throw new CommonException("当前服务不存在");
        }
        //判断当前服务是否处于草稿或者下架
        if(serve.getSaleStatus() == FoundationStatusEnum.DISABLE.getStatus()){
            throw new CommonException("当前服务已经处于下架状态或则草稿状态");
        }
        //业务处理
        //将服务状态改为下架
        serveService.lambdaUpdate()
                .eq(Serve::getId, serveId).setSql("sale_status = " + FoundationStatusEnum.DISABLE.getStatus())
                .update();
    }


    /**
     * 删除区域中的服务
     * @param serveId
     */
    @Override
    public void delete(Long serveId) {
        //参数校验
        if(serveId == null){
            throw new CommonException("参数不能为空");
        }
        Serve serve = serveService.getById(serveId);
        if(ObjectUtils.isEmpty(serve)){
            throw new CommonException("删除的服务已经不存在");
        }
        //判断当前服务是否处于草稿或者下架
        if(serve.getSaleStatus() != FoundationStatusEnum.INIT.getStatus()){
            throw new CommonException("当前服务不是草稿状态，不能删除！");
        }
        serveService.removeById(serveId);
    }


    /**
     * 设置服务为热门
     * @param serveId
     */
    @Override
    public void onHot(Long serveId) {
        //参数校验
        if(serveId == null){
            throw new CommonException("参数不能为空");
        }
        Serve serve = serveService.getById(serveId);
        if(ObjectUtils.isEmpty(serve)){
            throw new CommonException("当前服务不存在");
        }
        //判断当前服务所属项目是否处于启用状态
        ServeItem item = serveItemService.lambdaQuery().eq(ServeItem::getId, serve.getServeItemId()).one();
        if(item.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()){
            throw new CommonException("当前服务项目未启用");
        }
        //判断当前服务是否处于草稿或者下架
        if(serve.getSaleStatus() != FoundationStatusEnum.ENABLE.getStatus()){
            throw new CommonException("当前服务还未上架，需上架才能后设置热门");
        }
        //业务处理
        //将服务设置为热门状态
        serveService.lambdaUpdate()
                .eq(Serve::getId, serveId).setSql("is_hot = " + FoundationStatusEnum.DISABLE.getStatus())
                .update();
    }

    /**
     * 取消服务为热门
     * @param serveId
     */
    @Override
    public void offHot(Long serveId) {
        //参数校验
        if(serveId == null){
            throw new CommonException("参数不能为空");
        }
        Serve serve = serveService.getById(serveId);
        if(ObjectUtils.isEmpty(serve)){
            throw new CommonException("当前服务不存在");
        }
        //判断当前服务所属项目是否处于启用状态
        ServeItem item = serveItemService.lambdaQuery().eq(ServeItem::getId, serve.getServeItemId()).one();
        if(item.getActiveStatus() != FoundationStatusEnum.ENABLE.getStatus()){
            throw new CommonException("当前服务项目未启用");
        }
        //判断当前服务是否处于草稿或者下架
        if(serve.getSaleStatus() != FoundationStatusEnum.ENABLE.getStatus()){
            throw new CommonException("当前服务还未上架，需上架状态时才能修改热门状态");
        }
        //业务处理
        //将服务设置为非热门状态
        serveService.lambdaUpdate()
                .eq(Serve::getId, serveId).setSql("is_hot = " + FoundationStatusEnum.INIT.getStatus())
                .update();
    }
}
